<template>
  <div class="app-container">
    <el-row>
      <!--区域数据-->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input
            v-model="keyWordName"
            placeholder="输入关键字进行过滤"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
            v-loading="treeloading"
          >
            <span slot-scope="{ node, data }">
              <i v-if="data.treeType === 2" class="el-icon-school" style="color: #40a0ffd3;font-size: 12px;"></i>
              <span style="font-size: 13px;"> {{ node.label }}</span>
            </span>
          </el-tree>
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
<!--                <el-form-item label="设备归属水司" prop="tenantId">-->
<!--                  <el-input-->
<!--                    v-model="queryParams.tenantId"-->
<!--                    placeholder="请输入设备归属水司"-->
<!--                    clearable-->
<!--                    @keyup.enter.native="handleQuery"-->
<!--                    class="input_w"-->
<!--                  />-->
<!--                </el-form-item>-->
                <el-form-item label="用户编号" prop="UserID">
                  <el-input
                    v-model="queryParams.UserID"
                    placeholder="请输入用户编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="设备编号" prop="TerminalID">
                  <el-input
                    v-model="queryParams.TerminalID"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="集中器" prop="ConcentratorID">
                  <el-select v-model="queryParams.ConcentratorID" placeholder="请选择集中器" style="width: 100%" clearable>
                    <el-option v-for="item of concentratorOption" :key="item.ID" :label="item.ConcentratorName" :value="item.ID"></el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="楼栋编号" prop="ldId">
                  <el-input
                    v-model="queryParams.ldId"
                    placeholder="请输入楼栋编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item> -->
                <el-form-item label="IMEI" prop="IMEI">
                  <el-input
                    v-model="queryParams.IMEI"
                    placeholder="请输入IMEI"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="表状态" prop="TerminalMark">
                  <el-select v-model="queryParams.TerminalMark" placeholder="请选择表状态" style="width: 100%" clearable>
                    <el-option v-for="item of Terminalmark" :key="item.value" :label="item.label"
                              :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="通讯地址" prop="communicateAddress">
                  <el-input
                    v-model="queryParams.communicateAddress"
                    placeholder="请输入通讯地址"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item style="width: 0px">
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:terminalxb:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:terminalxb:remove']"
            >批量删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-tickets"
              size="mini"
              @click="handlewaitbind"
            >待绑户表</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleRegister"
            >NB平台注册</el-button>
          </el-col>
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport" :hasPermiExport="['basedata:terminalxb:export']" :uploadVisible="uploadVisible" @upload="handleUpload"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="terminalxbList" @selection-change="handleSelectionChange" max-height="600" ref="table">
          <el-table-column type="selection" width="55" align="center" fixed :selectable="selectable"/>
          <el-table-column label="编号" align="center" prop="ID" v-if="false" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="设备归属水司" align="center" prop="tenantId" width="120" v-if="columns[1].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="用户名称" align="center" prop="userName" v-if="columns[0].visible" :show-overflow-tooltip="true"  width="120"/>
          <el-table-column label="用户编号" align="center" prop="UserID" v-if="columns[1].visible" :show-overflow-tooltip="true"  width="120"/>
          <el-table-column label="门牌号" align="center" prop="roomName" v-if="columns[2].visible" :show-overflow-tooltip="true"  width="120"/>
          <el-table-column label="设备编号" align="center" prop="TerminalID" v-if="columns[3].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="IMEI" align="center" prop="IMEI" v-if="columns[4].visible" :show-overflow-tooltip="true" width="150"/>
          <!-- <el-table-column label="楼栋编号" align="center" prop="ldId" v-if="false" :show-overflow-tooltip="true"/>
          <el-table-column label="房间号" align="center" prop="roomId" v-if="false" :show-overflow-tooltip="true"/> -->
          <el-table-column label="厂家名称" align="center" prop="SupplierID" v-if="columns[5].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.SupplierID"/>
            </template>
          </el-table-column>
          <el-table-column label="表型号" align="center" prop="TypeID" v-if="columns[6].visible" :show-overflow-tooltip="true" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.TypeID"/>
            </template>
          </el-table-column>
          <el-table-column label="表底数" align="center" prop="BaseReading" v-if="columns[7].visible" :show-overflow-tooltip="true"/>
          <!-- (0：否，1：是) -->
          <el-table-column label="是否带阀控" align="center" prop="ValveControl" width="120" v-if="columns[8].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.ValveControl"/>
            </template>
          </el-table-column>
          <el-table-column label="阀门地址" align="center" prop="ValveAddress" v-if="columns[9].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="安装日期" align="center" prop="InstallDate" v-if="columns[10].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.InstallDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" align="center" prop="InstallAddress" v-if="columns[11].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="抄表周期" align="center" prop="MeterReaderCycle" v-if="columns[12].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.reader_cycle" :value="scope.row.MeterReaderCycle"/>
            </template>
          </el-table-column>
          <el-table-column label="表状态" align="center" prop="TerminalMark" v-if="columns[13].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.used_status" :value="scope.row.TerminalMark"/>
            </template>
          </el-table-column>
          <el-table-column label="协议名称" align="center" prop="protocolName" v-if="columns[14].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="通讯地址" align="center" prop="communicateAddress" v-if="columns[15].visible" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="集中器" align="center" prop="ConcentratorName" v-if="columns[16].visible" :show-overflow-tooltip="true" width="100" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-edit"
                size="mini"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:terminalxb:edit']"
                v-if="scope.row.TerminalMark === 1"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-coordinate"
                @click="handledeleteterminal(scope.row)"
                v-hasPermi="['basedata:terminalxb:remove']"
                v-if="scope.row.TerminalMark === 1"
              >销表</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-circle-close"
                style="color: #f5222d"
                v-if="scope.row.TerminalMark === 0"
              >已停用</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-monitor"
                @click="handleRemoteControl(scope.row)"
                v-if="scope.row.ConcentratorID == null && scope.row.CollectorID == null"
              >远程控制</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:terminalxb:remove']"
                v-if="scope.row.TerminalMark === 1"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改已绑定户表档案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="740px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择归属水司" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="设备编号" prop="TerminalID">
          <el-input v-model="form.TerminalID" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="IMEI" prop="IMEI">
          <el-input v-model="form.IMEI" placeholder="请输入IMEI" />
        </el-form-item>
        <el-form-item label="厂家名称" prop="SupplierID">
          <el-select v-model="form.SupplierID" filterable  placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表型号" prop="TypeID">
          <el-select v-model="form.TypeID" filterable  placeholder="请选择表型号" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表底数" prop="BaseReading">
          <el-input v-model="form.BaseReading" placeholder="请输入表底数" />
        </el-form-item>
        <el-form-item label="协议" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议" style="width: 202px;">
            <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId" :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通讯地址" prop="communicateAddress">
          <el-input v-model="form.communicateAddress" placeholder="请输入通讯地址" />
        </el-form-item>
        <el-form-item label="是否带阀控" prop="ValveControl">
          <el-select v-model="form.ValveControl" placeholder="请选择是否带阀控" style="width: 202px;">
            <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阀门地址" prop="ValveAddress">
          <el-input v-model="form.ValveAddress" placeholder="请输入阀门地址" />
        </el-form-item>
        <el-form-item label="抄表周期" prop="MeterReaderCycle">
          <el-select v-model="form.MeterReaderCycle" placeholder="请选择抄表周期" style="width: 202px;">
            <el-option v-for="dict in dict.type.reader_cycle" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装日期" prop="InstallDate">
          <el-date-picker clearable
            v-model="form.InstallDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择安装日期"
            style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装地址" prop="InstallAddress">
          <el-input v-model="form.InstallAddress" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="AEP平台的唯一码" prop="deviceId" v-if="title === '修改已绑定户表档案'">
          <el-input v-model="form.deviceId" placeholder="请输入AEP平台的唯一码" />
        </el-form-item>
        <el-form-item label="集中器" prop="ConcentratorID">
          <el-select v-model="form.ConcentratorID" placeholder="请选择集中器" style="width: 202px;" clearable>
            <el-option v-for="item of concentratorOption" :key="item.ID" :label="item.ConcentratorName" :value="item.ID.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="ReMark">
          <el-input v-model="form.ReMark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改未绑定户表档案对话框 -->
    <el-dialog :title="title" :visible.sync="nobindformopen" width="740px" append-to-body>
      <el-form ref="nobindform" :model="nobindform" :rules="nobindrules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="nobindform.tenantId" placeholder="请选择归属水司" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="设备编号" prop="TerminalID">
          <el-input v-model="nobindform.TerminalID" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="IMEI" prop="IMEI">
          <el-input v-model="nobindform.IMEI" placeholder="请输入IMEI" />
        </el-form-item>
        <el-form-item label="协议" prop="protocolId">
          <el-select v-model="nobindform.protocolId" placeholder="请选择协议" style="width: 202px;">
            <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId" :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂家名称" prop="SupplierID">
          <el-select v-model="nobindform.SupplierID" filterable  placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表型号" prop="TypeID">
          <el-select v-model="nobindform.TypeID" filterable  placeholder="请选择表型号" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表底数" prop="BaseReading">
          <el-input v-model="nobindform.BaseReading" placeholder="请输入表底数" />
        </el-form-item>
        <el-form-item label="通讯地址" prop="communicateAddress">
          <el-input v-model="nobindform.communicateAddress" placeholder="请输入通讯地址" />
        </el-form-item>
        <el-form-item label="是否带阀控" prop="ValveControl">
          <el-select v-model="nobindform.ValveControl" placeholder="请选择是否带阀控" style="width: 202px;">
            <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抄表周期" prop="MeterReaderCycle">
          <el-select v-model="nobindform.MeterReaderCycle" placeholder="请选择抄表周期" style="width: 202px;">
            <el-option v-for="dict in dict.type.reader_cycle" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阀门地址" prop="ValveAddress">
          <el-input v-model="nobindform.ValveAddress" placeholder="请输入阀门地址" />
        </el-form-item>
        <el-form-item label="安装日期" prop="InstallDate">
          <el-date-picker clearable
            v-model="nobindform.InstallDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择安装日期"
            style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装地址" prop="InstallAddress">
          <el-input v-model="nobindform.InstallAddress" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="AEP平台的唯一码" prop="deviceId">
          <el-input v-model="nobindform.deviceId" placeholder="请输入AEP平台的唯一码" />
        </el-form-item>
        <el-form-item label="集中器" prop="ConcentratorID">
          <el-select v-model="nobindform.ConcentratorID" placeholder="请选择集中器" style="width: 202px;" clearable>
            <el-option v-for="item of concentratorOption" :key="item.ID" :label="item.ConcentratorName" :value="item.ID.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="ReMark">
          <el-input v-model="nobindform.ReMark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitnobindForm">确 定</el-button>
        <el-button @click="onnobindCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 待绑户表 -->
    <el-dialog :title="title" :visible.sync="openWaitBind" width="calc(100w -200px)" append-to-body>
      <el-row>
        <el-form :model="nobindQueryParams" ref="nobindqueryForm" size="small"  :inline="true">
          <el-form-item label="设备编号" prop="TerminalID" label-width="90px">
            <el-input
              v-model="nobindQueryParams.TerminalID"
              placeholder="请输入设备编号"
              clearable
              @keyup.enter.native="handleQuerynobindTerminal"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="IMEI" prop="IMEI" label-width="60px">
            <el-input
              v-model="nobindQueryParams.IMEI"
              placeholder="请输入IMEI"
              clearable
              @keyup.enter.native="handleQuerynobindTerminal"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="通讯地址" prop="communicateAddress" label-width="90px">
            <el-input
              v-model="nobindQueryParams.communicateAddress"
              placeholder="请输入通讯地址"
              clearable
              @keyup.enter.native="handleQuerynobindTerminal"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="集中器" prop="ConcentratorID"  label-width="90px">
            <el-select v-model="nobindQueryParams.ConcentratorID" placeholder="请选择集中器" clearable class="input_w" @keyup.enter.native="handleQuerynobindTerminal">
              <el-option v-for="item of concentratorOption" :key="item.ID" :label="item.ConcentratorName" :value="item.ID.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuerynobindTerminal" size="mini">查询</el-button>
            <el-button @click="resetnobindTerminalQuery" size="mini">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-table v-loading="loading" :data="nobindxbList" max-height="500" ref="nobindtable">
          <el-table-column label="编号" align="center" prop="ID" v-if="false" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="归属水司" align="center" prop="tenantId" width="120" :show-overflow-tooltip="true"/> -->
          <el-table-column label="设备编号" align="center" prop="TerminalID" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="IMEI" align="center" prop="IMEI" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="厂家名称" align="center" prop="SupplierID" :show-overflow-tooltip="true" width="130">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.SupplierID"/>
            </template>
          </el-table-column>
          <el-table-column label="表型号" align="center" prop="TypeID" :show-overflow-tooltip="true" width="150">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.TypeID"/>
            </template>
          </el-table-column>
          <el-table-column label="表底数" align="center" prop="BaseReading" :show-overflow-tooltip="true"/>
          <el-table-column label="是否带阀控" align="center" prop="ValveControl" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.ValveControl"/>
            </template>
          </el-table-column>
          <el-table-column label="阀门地址" align="center" prop="ValveAddress" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="启用日期" align="center" prop="InstallDate" :show-overflow-tooltip="true" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.InstallDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" align="center" prop="InstallAddress" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="通讯地址" align="center" prop="communicateAddress" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="抄表周期" align="center" prop="MeterReaderCycle" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.reader_cycle" :value="scope.row.MeterReaderCycle"/>
            </template>
          </el-table-column>
          <el-table-column label="协议" align="center" prop="protocolName" :show-overflow-tooltip="true"/>
          <el-table-column label="集中器" align="center" prop="ConcentratorName" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-edit"
                size="mini"
                @click="handlenobindUpdate(scope.row)"
                v-hasPermi="['basedata:terminalxb:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handlenobindDelete(scope.row)"
                v-hasPermi="['basedata:terminalxb:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="nobindtotal>0"
          :total="nobindtotal"
          :page.sync="nobindQueryParams.pageNum"
          :limit.sync="nobindQueryParams.pageSize"
          @pagination="getnobindList"
        />
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onOk">确 定</el-button>
        <el-button @click="onCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <!-- <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div> -->
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 远程控制对话框 -->
    <el-dialog :title="title" :visible.sync="openReomteControl" width="700px" append-to-body @close="closeReomoteDialog">
      <el-form ref="reomtecontrolform" :model="reomteControlForm" :rules="remoteControlRules" :label-width="labelWidth" :inline="true">
        <el-form-item label="命令类型" prop="commandType">
          <el-select v-model="reomteControlForm.commandType" filterable  placeholder="请选择命令类型" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.command_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isOpen">
          <el-radio-group v-model="reomteControlForm.isOpen">
            <el-radio label="1">开</el-radio>
            <el-radio label="2">关</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 提示信息 -->
      <el-alert
        :title="alert.alertContent"
        :type="alert.alertType"
        :closable="false"
        v-if="alert.alertContent != null && alert.alertContent != ''">
      </el-alert>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendForm" :disabled="submitdisabled">发送</el-button>
      </div>
    </el-dialog>
    <RegisterDialog :dialogTitle="register.title" :dialogVisible="register.open" @isClose="isClose" @getList="getList"></RegisterDialog>
  </div>
</template>

<script>
  import moment from 'moment'
import { listTerminalxb, getTerminalxb, delTerminalxb, addTerminalxb, updateTerminalxb, cancelterminal, remoteControl } from "@/api/record/terminalxb";
import { selectProtocol } from '@/api/basedata/protocol.js'
import { getToken } from "@/utils/auth";
import RegisterDialog from '../component/registerDialog.vue'
import { concentratorOption } from '@/api/record/concentrator'

export default {
  name: "Terminalxb",
  components: { RegisterDialog },
  dicts: ['yes_no', 'used_status', 'belong_department', 'module_type', 'command_type', 'terminal_supplier', 'reader_cycle'],
  data() {
    return {
      submitdisabled: false,
      uploadVisible: true,
      // 远程控制提示信息
      alert: {
        alertContent: null,
        alertType: 'success'
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/terminalxb/importData"
      },
      // 协议下拉框中的数据
      protocolOption: [],
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '130px',
      // 列信息
      columns: [
        // { key: 0, label: `自增主键`, visible: false },
        // { key: 1, label: `设备归属水司`, visible: false },
        { key: 0, label: `用户名称`, visible: true },
        { key: 1, label: `用户编号`, visible: true },
        { key: 2, label: `门牌号`, visible: true },
        { key: 3, label: `设备编号`, visible: true },
        { key: 4, label: `IMEI`, visible: true },
        { key: 5, label: `厂家名称`, visible: true },
        { key: 6, label: `表型号`, visible: true },
        { key: 7, label: `表底数`, visible: true },
        { key: 8, label: `是否带阀控`, visible: true },
        { key: 9, label: `阀门地址`, visible: true },
        { key: 10, label: `安装日期`, visible: true },
        { key: 11, label: `安装地址`, visible: true },
        { key: 12, label: `抄表周期`, visible: true },
        { key: 13, label: `表状态`, visible: true },
        { key: 14, label: `协议名称`, visible: true },
        { key: 15, label: `通讯地址`, visible: true },
        { key: 16, label: `集中器`, visible: true },
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      treeloading: false,
      AreaName:'',
      // 区域树选项
      areaOptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      terminalids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      nobindtotal: 0,
      // 小档案表格数据
      terminalxbList: [],
      nobindxbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openWaitBind: false,
      nobindformopen: false,
      openReomteControl: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        TerminalID: null,
        UserID: null,
        ldId: null,
        treeAreaCode: null,
        treeLdId: null,
        isBound: true,
        IMEI: null,
        communicateAddress: null,
        TerminalMark: 1,
        ConcentratorID: null,
      },
      nobindQueryParams:{
        pageNum: 1,
        pageSize: 20,
        TerminalID: null,
        isBound: false,
        IMEI: null,
        communicateAddress: null,
        ConcentratorID: null,
      },
      // 表单参数
      form: {
        tenantId: '710170'
      },
      Terminalmark: [
        {label: '全部', value: null},
        {label: '正常', value: 1},
        {label: '停用', value: 0},
      ],
      // 集中器下拉框
      concentratorOption: [],
      nobindform: {},
      // 远程控制表单
      reomteControlForm: {
        commandType: "0",
        isOpen: '1'
      },
      terminalInfoObj: {},
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "归属水司不能为空", trigger: "change" }
        // ],
        TerminalID: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        //IMEI: [
        //  { required: true, message: "IMEI不能为空", trigger: "blur" }
        //],
        SupplierID: [
          { required: true, message: "厂家名称不能为空", trigger: "change" }
        ],
        // protocolId: [
        //   { required: true, message: "协议名称不能为空", trigger: "change" }
        // ],
        communicateAddress: [
          { required: true, message: "通讯地址不能为空", trigger: "blur" }
        ],
      },
      nobindrules: {
        // tenantId: [
        //   { required: true, message: "归属水司不能为空", trigger: "change" }
        // ],
        // IMEI: [
        //   { required: true, message: "IMEI不能为空", trigger: "blur" }
        // ],
        TerminalID: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        SupplierID: [
          { required: true, message: "厂家名称不能为空", trigger: "change" }
        ],
        // protocolId: [
        //   { required: true, message: "协议名称不能为空", trigger: "change" }
        // ],
        communicateAddress: [
          { required: true, message: "通讯地址不能为空", trigger: "blur" }
        ],
      },
      remoteControlRules: {
        commandType: [
          { required: true, message: "请选择命令类型", trigger: "change" }
        ],
        isOpen: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
      },
      register: {
        title: 'NB平台注册',
        open: false,
      },
      registerform: {
        IMEI: '',
      }
    };
  },
  created() {
    this.getAreaTree();
  },
  mounted() {
    this.getList();
    this.getnobindList()
    this.getSelectProtocol();
    this.getConcentratorOption()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
    AreaName(val){
      this.$refs.areatree.filter(val)
    }
  },
  methods: {
    // 获取集中器下拉框中的数据
    getConcentratorOption(){
      concentratorOption().then(response => {
        this.concentratorOption = response.rows
      })
    },
    // 关闭远程控制对话框
    closeReomoteDialog(){
      this.$refs.reomtecontrolform.resetFields()
      this.submitdisabled = false
    },
    // 打开注册对话框
    handleRegister(){
      this.register.open = true
      // this.registerform.IMEI = ''
      this.register.title = 'NB平台注册'
    },
    // 关闭注册弹框
    isClose(val){
      this.register.open = !val
    },
    // 判断表的状态禁用表格多选按钮
    selectable(row, rowIndex){
      if(row.TerminalMark === 1){
        return true;  //不禁用
      }else {
        return false;  //禁用
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "户表档案导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 获取协议下拉框中的数据
    getSelectProtocol(){
      let TerminalType = 2
      selectProtocol(TerminalType).then(response => {
        this.protocolOption = response.data
      })
    },
    filterValue(query){
      if (query !== "") {
        this.areaOptions = this.areaOptions((item) => {
          if(item.areaName.toLowerCase().indexOf(query) > -1){
            return item
          }
        })
      } else {
        this.areaOptions = [];
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.resetQueryParams();
      if( data.treeType === 1){
        this.queryParams.treeAreaCode = data.areaCode;
        this.getList()
      }else if(data.treeType === 2){
        this.queryParams.treeLdId = data.ldId
        this.getList()
      }
    },
    // 单击下拉框中的数据
    handleSelectTree(data){
      this.form.AreaCode = data.id
    },
     /** 查询区域下拉树结构 */
     getAreaTree() {
      this.treeloading = true
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        if(item.children === null){
          item.children = []
        }
        if(item.louDongs !=null && item.louDongs !=[]){
          item.children = item.children.concat(item.louDongs)
        }
        let childrens = item.children
        let obj = {
          id: item.treeType === 1?  item.areaCode : item.id,
          label: item.treeType === 1? item.areaName : item.ldName,
          children: item.children && item.children.length > 0 ? this.copyTree(childrens) : item.childrens
        }
        this.areaOptions.push(obj)
        this.treeloading = false
      })
    },
    copyTree(list) {
      list.forEach((item) => {
        let flag1 = false
        let childrens = []
        if((null != item.children  && item.children.length > 0)||(null != item.louDongs  && item.louDongs.length > 0)){
          flag1 = true
          if(item && item.children && item.louDongs){
            childrens = item.children.concat(item.louDongs)
          }else if(item && item.children && item.louDongs == null){
            childrens = item.children
          }else if(item && item.louDongs && item.children == null ){
            childrens = item.louDongs
          }
        }else{
          flag1 = false
        }
        item.id = item.treeType === 1?  item.areaCode : item.id;
        item.label = item.treeType === 1? item.areaName : item.ldName;
        item.children = childrens;
        if (flag1) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow(){
      this.treeVisibale =!this.treeVisibale
    },
    /** 查询已绑定小档案列表 */
    getList() {
      this.loading = true;
      listTerminalxb(this.queryParams).then(response => {
        this.terminalxbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getnobindList(){
      this.loading = true;
      listTerminalxb(this.nobindQueryParams).then(response => {
        this.nobindxbList = response.rows;
        this.nobindtotal = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        tenantId: '710170',
        TerminalID: null,
        ldId: null,
        roomId: null,
        UserID: null,
        SupplierID: null,
        TypeID: null,
        BaseReading: null,
        ValveControl: null,
        ValveAddress: null,
        InstallDate: null,
        InstallAddress: null,
        ChangeMark: null,
        terminalNew: null,
        DeleteMark: null,
        MeterReaderCycle: null,
        ReMark: null,
        TerminalMark: null,
        protocolId: null,
        communicateAddress: null,
        IMEI: null,
        ConcentratorID: null,
        deviceId: null,
      };
      this.resetForm("form");
    },
    // 表单重置
    nobindformreset() {
      this.nobindform = {
        ID: null,
        tenantId: null,
        TerminalID: null,
        SupplierID: null,
        TypeID: null,
        BaseReading: null,
        ValveControl: null,
        ValveAddress: null,
        InstallDate: null,
        InstallAddress: null,
        ChangeMark: null,
        terminalNew: null,
        DeleteMark: null,
        MeterReaderCycle: null,
        ReMark: null,
        TerminalMark: null,
        protocolId: null,
        communicateAddress: null,
        IMEI: null,
        deviceId: null,
        ConcentratorID: null,
      };
      this.resetForm("nobindform");
    },
    // 远程控制表单重置
    resetReomteControl(){
      this.reomteControlForm = {
        commandType: "0",
        isOpen: '1'
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQuerynobindTerminal(){
      this.nobindQueryParams.pageNum = 1;
      this.getnobindList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.tree.setCurrentKey(null);
      this.queryParams.treeLdId = null;
      this.queryParams.treeAreaCode = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetnobindTerminalQuery(){
      this.nobindQueryParams.ConcentratorID = null
      this.resetForm("nobindqueryForm");
      this.handleQuerynobindTerminal();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.terminalids = selection.map(item => item.TerminalID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 添加户表档案按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加户表档案";
    },
    // 远程控制按钮 弹出框
    handleRemoteControl(row){
      this.resetReomteControl();
      const ID = row.ID
      getTerminalxb(ID).then(response => {
        this.terminalInfoObj= response.data;
        this.openReomteControl = true;
        this.title = "远程控制";
      });
      this.alert.alertContent = ""
    },
    /** 修改已绑定户表档案按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getTerminalxb(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改已绑定户表档案";
      });
    },
    /** 修改未绑定户表档案按钮操作 */
    handlenobindUpdate(row) {
      this.nobindformreset();
      getTerminalxb(row.ID).then(response => {
        this.nobindform = response.data;
        this.nobindformopen = true;
        this.title = "修改未绑定户表档案";
      });
    },
    // 待绑户表按钮操作
    handlewaitbind(){
      this.resetnobindTerminalQuery()
      this.title = "未绑定户表"
      this.openWaitBind = true,
      this.handleQuerynobindTerminal()
    },
    // 远程控制发送
    sendForm(){
      this.$refs["reomtecontrolform"].validate(valid => {
        if(valid){
          let form = this.terminalInfoObj
          form.commandType = this.reomteControlForm.commandType
          form.isOpen = this.reomteControlForm.isOpen
          remoteControl(form).then(response =>{
            this.alert.alertContent = moment(new Date()).format("YYYY-MM-DD HH:mm:ss") + ":" + response.msg
            if(response.code == 200){
              this.alert.alertType = 'success'
            }else{
              this.alert.alertType = "error"
            }
          })
        }
      })
    },
    /** 已绑定提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "修改已绑定户表档案") {
            updateTerminalxb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else if(this.title === "添加户表档案") {
            addTerminalxb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitnobindForm(){
      this.$refs["nobindform"].validate(valid => {
        if (valid) {
          updateTerminalxb(this.nobindform).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.nobindformopen = false;
            this.getnobindList();
          });
        }
      });
    },
    /** 已绑定删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      const terminalIDs = row.TerminalID || this.terminalids;
      this.$modal.confirm('是否确认删除户表档案编号为"' + terminalIDs + '"的数据项？').then(function() {
        return delTerminalxb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 未绑定删除按钮操作 */
    handlenobindDelete(row){
      const IDs = row.ID
      this.$modal.confirm('是否确认删除户表档案编号为"' + row.TerminalID + '"的数据项？').then(function() {
        return delTerminalxb(IDs);
      }).then(() => {
        this.getnobindList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/terminalxb/export', {
        ...this.queryParams
      }, `terminalxb_${new Date().getTime()}.xlsx`)
    },
    // 下载模板
    handleUpload(){
      this.download('basedata/terminalxb/getImportTemplate', {
      }, `户表档案模板_${new Date().getTime()}.xlsx`)
    },
    // 销表
    handledeleteterminal(row){
      debugger
      this.reset()
      // 1使用中 0停用
      this.form = row
      if(row.TerminalMark === 1){
        this.$modal.confirm('是否确认停用编号为"' + row.TerminalID + '"的表？').then(() =>{
          return cancelterminal(this.form)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("销表成功!");

        }).catch(() => {});
      }else if(row.TerminalMark === 0){
        this.$modal.msgWarning("此表已停用！");
      }
    },
    // 查看未绑定
    onOk(){
      this.openWaitBind = false
      this.resetForm("nobindqueryForm");
    },
    onCancel(){
      this.openWaitBind = false
      this.resetForm("nobindqueryForm");
    },
    onnobindCancel(){
      this.nobindformopen = false
      this.nobindformreset()
    }
  }
};
</script>
<style lang="scss" scoped>
  .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
</style>
